package com.seabook.store.purchase.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.seabook.store.auth.domain.User;
import com.seabook.store.auth.service.UserService;
import com.seabook.store.auth.web.UserSession;
import com.seabook.store.goodmgr.service.ProductService;
import com.seabook.store.purchase.domain.Cart;
import com.seabook.store.purchase.domain.Order;
import com.seabook.store.util.ServiceLocator;

@Controller
@SessionAttributes(types = Order.class)
public class CheckOutController {
    private final ProductService productService;
    
    private final UserService userService;

    public CheckOutController() {
        this.productService = (ProductService) ServiceLocator
                .getBean("productService");
        this.userService = (UserService)ServiceLocator.getBean("userService");
    }

    @RequestMapping(value = "/order/checkout", method = RequestMethod.GET)
    public String checkout(Model model, HttpServletRequest request) {
        User user = UserSession.getUserSession(request).getUser();
        if (null == user || user.getUserId() == 0) {
            request.setAttribute("msg.need.login",
                    "Please login to continue the operation.");
            request.setAttribute("forwardAction", "checkout.do");
            return "login";
        }
        Cart cart = UserSession.getUserSession(request).getCart();
        user = userService.getUserInfo(user);
        
        Order order = new Order();
        order.initOrder(user.getDefaultAddress(), cart);
        request.setAttribute("order", order);
        request.setAttribute("user", user);
        model.addAttribute(order);
        return "confirmOrder";
    }

}
